import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
// import { VERSION_NEUTRAL, VersioningType } from '@nestjs/common';
import { AllExceptionsFilter } from './common/exceptions/base.exception.filter';
import { HttpExceptionFilter } from './common/exceptions/http.exception.filter';
import { generateDocument } from './doc';
import { TransformInterceptor } from './common/interceptor/transform/transform.interceptor';
import { limiter } from './common/rate-limit.middleware';
import { NextFunction, Request, Response } from 'express';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 限制请求次数
  app.use(limiter);

  // 设置接口前缀
  // app.setGlobalPrefix('api');

  // 版本控制
  // app.enableVersioning({
  //   type: VersioningType.URI,
  //   defaultVersion: [VERSION_NEUTRAL, '1'],
  // });

  // 关键安全头配置
  app.enableCors({
    origin: true, // 按需替换为具体域名
    methods: 'GET,POST,PATCH,PUT,DELETE',
    allowedHeaders: 'Content-Type,Authorization',
  });

  app.use((_req: Request, res: Response, next: NextFunction) => {
    // 强制浏览器遵守 Referrer 策略
    res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
    next();
  });

  // 异常过滤
  app.useGlobalFilters(new AllExceptionsFilter(), new HttpExceptionFilter());

  // 响应拦截
  app.useGlobalInterceptors(new TransformInterceptor());
  // 接口文档
  generateDocument(app);
  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
